import { Button, Form, Input, message } from "antd";
import { useForm } from "antd/es/form/Form";
import "./index.scss";
import { login } from "../../interfaces";
import { useNavigate, Link, useSearchParams } from "react-router-dom";
import { useEffect } from "react";
import { GFS } from "@/hooks/useAssignGlobalProps";
interface LoginUser {
  username: string;
  password: string;
}

const layout1 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const layout2 = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

export default function Login() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams();
  const [form] = useForm();
  useEffect(()=>{
    const username = searchParams.get('username')
    const password = searchParams.get('password')
    form.setFieldsValue({username, password})
  },[])
  const onFinish = async(values: LoginUser) => {
    try{
      const res = await login(values.username, values.password)
      if(res.status === 200 || res.status === 201){
        GFS.message.success('登录成功')
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('userInfo', JSON.stringify(res.data.user));

        setTimeout(() => {
          navigate('/')
        }, 1000);
      }
    }catch(e: any){
      GFS.message.error(e.response?.data?.message || '登录失败')
    }
  };
  return (
    <div id="login-container">
      <h1 className="mb-5 text-xl font-bold">jedi-admin</h1>
      <Form form={form} {...layout1} onFinish={onFinish} colon={false} autoComplete="off">
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item {...layout1} label=" ">
          <div className="links">
            <Link to="/register">创建账号</Link>
            <Link to="/update_password">忘记密码</Link>
          </div>
        </Form.Item>

        <Form.Item {...layout1} label=" ">
          <Button className="btn" type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
